<template>
  <div class="container">
    <el-card>
      <div class="add-wrap">
        <el-button @click="openDialog" type="primary" plain>
          <el-icon><CirclePlus /></el-icon>
          <span>添加数据库连接</span>
        </el-button>
      </div>
      <div class="table-wrapper">
        <el-table
          :data="tableData"
          border
          style="width: 100%"
          :row-class-name="rowClassName"
          max-height="calc(100vh - 300px)"
        >
          <el-table-column label="序号" width="60">
            <template #default="scope">
              {{ scope.row.index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="url" label="url" />
          <el-table-column prop="username" label="用户名称" width="100" />
          <el-table-column prop="dbname" label="数据库" width="100" />
          <el-table-column prop="dbtitle" label="数据库名称" width="100" />
          <el-table-column prop="dbtype" label="数据库类型" width="120" />
          <el-table-column prop="dbtype" label="连接状态" width="120">
            <template #default="scope">
              {{ scope.row.invalid == 1 ? "离线" : "在线" }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-tooltip class="box-item" effect="dark" content="初始化向量库" placement="top">
                <el-icon
                  color="#0C6BED"
                  size="16"
                  @click="init(scope.row)"
                  class="edit-btn"
                  v-if="scope.row.invalid != '1'"
                  ><Refresh />
                </el-icon>
              </el-tooltip>
              <el-tooltip class="box-item" effect="dark" content="数据库重连" placement="top">
                <el-icon
                  color="#0C6BED"
                  size="16"
                  @click="tryConnect(scope.row)"
                  class="edit-btn"
                  v-if="scope.row.invalid == '1'"
                  ><Connection
                /></el-icon>
              </el-tooltip>
              <el-tooltip class="box-item" effect="dark" content="编辑" placement="top">
                <el-icon color="#0C6BED" size="16" @click="updateCon(scope.row)" class="edit-btn"><Edit /></el-icon>
              </el-tooltip>

              <el-tooltip class="box-item" effect="dark" content="删除" placement="top">
                <el-icon color="#E34D59" size="16" @click="clickDel(scope.row)"><Delete /></el-icon>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    <!-- 添加弹窗 -->
    <el-dialog v-model="dialogFormVisible" title="添加数据库连接" width="600">
      <el-form ref="formRef" :model="form" :rules="rules">
        <el-form-item prop="url" label="url：" :label-width="formLabelWidth">
          <el-input v-model="form.url" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="username" label="用户名称：" :label-width="formLabelWidth">
          <el-input v-model="form.username" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="password" label="用户密码：" :label-width="formLabelWidth">
          <el-input v-model="form.password" type="password" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="dbname" label="数据库：" :label-width="formLabelWidth">
          <el-input v-model="form.dbname" autocomplete="off" :disabled="form.did" />
        </el-form-item>
        <el-form-item prop="dbtitle" label="数据库名称：" :label-width="formLabelWidth">
          <el-input v-model="form.dbtitle" autocomplete="off" :disabled="form.did" />
        </el-form-item>
        <el-form-item label="数据库类型：" :label-width="formLabelWidth">
          <el-input v-model="form.dbtype" disabled autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetFields">取消</el-button>
          <el-button type="primary" @click="updateTable(formRef)" v-if="form.did"> 确认修改 </el-button>
          <el-button type="primary" @click="addTable(formRef)" v-else> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from "vue"
import { ElMessage, ElLoading, ElMessageBox } from "element-plus"
import { dbconnect, delDbconnect, getDbconnect, dbreconnect, updateConnect, initdb } from "@/api/sql"

onMounted(() => {
  getTableData()
})

const dialogFormVisible = ref(false)
const formRef = ref()
const form = ref({
  url: "",
  username: "",
  password: "",
  dbname: "",
  dbtitle: "",
  dbtype: "MySQL"
})
const rules = reactive({
  url: [{ required: true, message: "url必填", trigger: "blur" }],
  username: [{ required: true, message: "用户名必填", trigger: "blur" }],
  password: [{ required: true, message: "密码必填", trigger: "blur" }],
  dbname: [{ required: true, message: "数据库必填", trigger: "blur" }],
  dbtitle: [{ required: true, message: "数据库名称必填", trigger: "blur" }]
})

const formLabelWidth = "110px"
const tableData = ref([])
// 更新
async function updateCon(row) {
  form.value = row
  console.log(form.value, "form.value")

  // 展示弹窗
  dialogFormVisible.value = true
}

async function init(row) {
  const { code } = await initdb({ dbname: row.dbname })
  if (code === 200) {
    ElMessage.success("初始化向量库成功")
    getTableData()
  }
}
// 重连
async function tryConnect(row) {
  const { code } = await dbreconnect({ did: row.did })
  if (code === 200) {
    ElMessage.success("重连成功")
    getTableData()
  }
}
// 删除
const clickDel = (para) => {
  ElMessageBox.confirm("确认删除当前数据吗?", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    delTr(para)
  })
}
async function delTr(row) {
  const { code } = await delDbconnect({ did: row.did })
  if (code === 200) {
    ElMessage.success("删除成功")
    tableData.value.splice(row.index, 1)
  }
}
function rowClassName({ row, rowIndex }) {
  row.index = rowIndex
}
function openDialog() {
  // 重置内容
  form.value = {
    url: "",
    username: "",
    password: "",
    dbname: "",
    dbtitle: "",
    dbtype: "MySQL"
  }
  formRef.value?.resetFields()
  form.value.dbtype = "MySQL"
  console.log(form.value, " form.value.")

  dialogFormVisible.value = true
}
function resetFields() {
  dialogFormVisible.value = false
}
async function updateTable() {
  formRef.value
    .validate()
    .then(async () => {
      const { code } = await updateConnect({
        ...form.value
      })
      if (code === 200) {
        ElMessage.success("添加成功")
        formRef.value?.resetFields()
        // clearTheObj(form.value)
        form.value.dbtype = "MySQL"
        dialogFormVisible.value = false
        getTableData()
      }
    })
    .catch((err) => {
      console.log("验证失败", err)
    })
}
async function addTable() {
  formRef.value
    .validate()
    .then(async () => {
      const { code } = await dbconnect({
        ...form.value
      })
      if (code === 200) {
        ElMessage.success("添加成功")
        formRef.value?.resetFields()
        // clearTheObj(form.value)
        form.value.dbtype = "MySQL"
        dialogFormVisible.value = false
        getTableData()
      }
    })
    .catch((err) => {
      console.log("验证失败", err)
    })
}
// const clearTheObj = (obj) => {
//   const emptyArr = {}
//   for (const key in obj) {
//     emptyArr[key] = null
//   }
//   Object.assign(obj, emptyArr)
// }
async function getTableData() {
  const wrap = document.getElementsByClassName("table-wrapper")[0]
  const loadingInstance = ElLoading.service({
    target: wrap,
    text: "Loading"
  })
  const { code, data } = await getDbconnect()
  if (code === 200) {
    tableData.value = data
  }
  loadingInstance.close()
}
</script>
<style lang="scss" scoped>
::v-deep(.el-form-item__content) {
  flex: none;
  width: 430px !important;
}
/* 设置表头背景色 */
::v-deep(.el-table__header-wrapper th) {
  background-color: #f5f5f5; /* 背景色 */
  color: #333; /* 文字颜色 */
  font-weight: bold; /* 加粗字体 */
}
.edit-btn {
  margin-right: 15px;
}
.search-ipt {
  width: 250px;
}
.add-wrap {
  display: flex;
  margin-bottom: 20px;
}
.table-wrapper {
  margin-bottom: 20px;
}
</style>
